package boot

import (
	"awesome-devops/applications/tools"
	"fmt"
	"gitee.com/jjawesomejj/awesome-util/config"
	"gitee.com/jjawesomejj/awesome-util/echo"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	"os"
	"strings"
)

type EnvService struct {
}

func (service *EnvService) Init() {
	pub := getEnv("SSH_PUB", "")
	if pub != "" {
		//fmt.Println(pub)
	} else {
		return
	}
	pub = strings.Trim(pub, " ")
	pub = pub + "\n"
	privateKey := getEnv("SSH_PRIVATE", "")
	if privateKey != "" {
		//fmt.Println(privateKey)
	} else {
		return
	}
	privateKey = strings.ReplaceAll(privateKey, "-----BEGIN RSA PRIVATE KEY-----", "")
	privateKey = strings.ReplaceAll(privateKey, "-----END RSA PRIVATE KEY-----", "")
	privateKey = strings.Trim(privateKey, " ")
	privateKey = strings.ReplaceAll(privateKey, " ", "\n")
	privateKey = strings.ReplaceAll(privateKey, "\n\n", "\n")
	privateKey = "-----BEGIN RSA PRIVATE KEY-----" + "\n" + privateKey + "-----END RSA PRIVATE KEY-----"
	//fmt.Println(privateKey)
	res := tools.GetKernelDriver().ExecShellOrBashAsync("mkdir ~/.ssh")
	err := res.Run()
	//if err != nil {
	//	fmt.Println(err)
	//}
	//fmt.Println(commonhelper.Format("cat <<EOF >~/.ssh/id_rsa \n{}EOF\n", privateKey))
	_, err = tools.GetKernelDriver().ExecShellOrBash(commonhelper.Format("cat <<EOF >~/.ssh/id_rsa \n{}\n", privateKey), false)
	if err != nil {
		fmt.Println(err)
	}
	_, err = tools.GetKernelDriver().ExecShellOrBash(commonhelper.Format("cat <<EOF >~/.ssh/id_rsa.pub \n{}EOF\n", pub), false)
	if err != nil {
		fmt.Println(err)
	}
	config.SetConfigByKey("ssh_pub", pub)
	config.SetConfigByKey("ssh_private", privateKey)
	tools.GetKernelDriver().ExecShellOrBash("echo \"StrictHostKeyChecking no\" > ~/.ssh/config", false)
	tools.GetKernelDriver().ExecShellOrBash("chmod 700 ~/.ssh/", false)
	tools.GetKernelDriver().ExecShellOrBash("chmod 644 ~/.ssh/id_rsa.pub", false)
	tools.GetKernelDriver().ExecShellOrBash("chmod 600 ~/.ssh/id_rsa", false)
	echo.Green("读取到环境变量中的ssh key")

}

func getEnv(key string, defaultValue string) string {
	if value, ok := os.LookupEnv(key); ok {
		return value
	}

	return defaultValue
}
